package com.zqy.common.intercept;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.zqy.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Token拦截器
 */

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断状态
        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        //返回数据格式
        response.setContentType("application/json;charset=UTF-8");
        //设置编码
        response.setCharacterEncoding("utf-8");
        // 从 http 请求头中取出 token
        String token = request.getHeader("token");
        System.out.println("token   :"+token);//输出token
        //如果携带没有携带token,则返回null
        if(StringUtil.isEmpty(token)){
            response.getWriter().write("未携带Token信息,或许根本不存在");
            return  false;
        }


        if(token != null){
            //验证token是否正确
            Claims claims = JwtUtil.parseJwt(token);


              return true;
        }






        return false;

    }
    /**
     * 在Controller调用方法后（请求处理之后进行调用，但是在视图被渲染之前）
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle执行");
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion执行");
    }





}
